package com.inhim.pjhim.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.inhim.pjhim.R;
import com.inhim.pjhim.adapter.SearchAdapter;
import com.inhim.pjhim.adapter.SearchClassfiyAdapter;
import com.inhim.pjhim.adapter.SearchReultListAdapter;
import com.inhim.pjhim.adapter.TagReaderListAdapter;
import com.inhim.pjhim.app.BaseActivity;
import com.inhim.pjhim.entity.ReaderBean;
import com.inhim.pjhim.entity.ReaderList;
import com.inhim.pjhim.entity.ReaderTagList;
import com.inhim.pjhim.entity.ReaderTwo;
import com.inhim.pjhim.entity.ReaderTypeList;
import com.inhim.pjhim.entity.TagReaderList;
import com.inhim.pjhim.http.MyOkHttpClient;
import com.inhim.pjhim.http.Urls;
import com.inhim.pjhim.utils.BeanConvertor.BeanConvertor;
import com.inhim.pjhim.widget.AuthorWidget;

import org.yczbj.ycrefreshviewlib.view.YCRefreshView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Request;

/**
 * Created by hsmacmini on 2018/4/4.
 */

public class SearchNewActivity extends BaseActivity {

    /**
     * 搜索结果列表view
     */
    //private ListView lvResults;


    /**
     * 搜索结果列表adapter
     */
    private SearchAdapter resultAdapter;

    /**
     * 搜索结果的数据
     */
    private List<ReaderList.List> resultData1;


    private ImageView search_iv;
    private RecyclerView rv_class;
    private RecyclerView main_lv_search_results;
    private YCRefreshView ycRefreshView;
    private Gson gson;
//    private SearchTagAdapter mSearchTagAdapter;
    private List<ReaderTagList.List> mReaderTagList;
    private TagReaderListAdapter mTagReaderListAdapter;
    private TextView tv_cacel;
    private EditText search_et_input;
    private List mTagReaderList = new ArrayList();
    private TextView tv_lable;
    private View view_lin;
    private AuthorWidget authorWidget;
    private SearchClassfiyAdapter classfiyAdapter;
    private SearchReultListAdapter searchReultListAdapter;

    @Override
    public Object offerLayout() {
        return R.layout.activity_new_search;
    }

    @Override
    public void onBindView() {
        gson = new Gson();
        initViews();
//        getReaderTagList();
    }

    @Override
    public void destory() {

    }


    private void getReaderList(final String keyword) {
        /** {
         "readerStyleId": "string",
         "readerStyleValueId": "string",
         "readerTypeId": "string",
         "title": "string"
         }*/
        HashMap postMap = new HashMap();
        postMap.put("title", keyword);
        MyOkHttpClient.getInstance().asyncJsonPostNoToken(Urls.getReaderList(1, 100, "desc"), postMap, new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {

            }

            @Override
            public void onSuccess(Request request, String result) {
                //main_lv_search_results.setVisibility(View.GONE);
                mTagReaderList.clear();
                ReaderBean readerList = gson.fromJson(result, ReaderBean.class);

                boolean showAuthorWidget = readerList.getAuthorList()!=null&&readerList.getAuthorList().size()>0;
                if (showAuthorWidget) {
                    ReaderBean.AuthorList author=readerList.getAuthorList().get(0);
                    authorWidget.setData(author.getHeadPortrait(),author.getName(),author.getArea(),author.getSynopsis());
                    authorWidget.setVisibility(View.VISIBLE);
                }else {
                    authorWidget.setVisibility(View.GONE);
                }
                if (readerList.getTypeList()!=null&&readerList.getTypeList().size()>0) {
                    classfiyAdapter.setListBeans(readerList.getTypeList());
                    tv_lable.setVisibility(View.VISIBLE);
                    rv_class.setVisibility(View.VISIBLE);
                }else {
                    rv_class.setVisibility(View.GONE);
                    tv_lable.setVisibility(View.GONE);
                }
                if (!showAuthorWidget&&readerList.getPage()!=null&&readerList.getPage().getList()!=null){
                    searchReultListAdapter.setListBeans(readerList.getPage().getList());
                }else {
                    searchReultListAdapter.setListBeans(new ArrayList<>());
                }
                InputMethodManager manager = ((InputMethodManager)search_et_input.getContext().getSystemService(Context.INPUT_METHOD_SERVICE));
                if (manager != null)
                    manager.hideSoftInputFromWindow(search_et_input.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

            }
        });
    }

    /**
     * 初始化视图
     */

    private void initViews() {
        view_lin=findViewById(R.id.view_lin);
        tv_lable=findViewById(R.id.tv_lable);
        search_et_input = findViewById(R.id.search_et_input);
        search_et_input.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //当actionId == XX_SEND 或者 XX_DONE时都触发
                //或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN时也触发
                //注意，这是一定要判断event != null。因为在某些输入法上会返回null。
                if (actionId == EditorInfo.IME_ACTION_SEND
                        || actionId == EditorInfo.IME_ACTION_DONE
                ||actionId==EditorInfo.IME_ACTION_SEARCH){
                        //|| (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
                    //处理事件
                    if(!"".equals(search_et_input.getText().toString().trim())){
                        getReaderList(search_et_input.getText().toString().trim());
                    }
                }
                return false;
            }
        });
        // 分类
        rv_class = findViewById(R.id.rv_class);
        rv_class.setLayoutManager(new LinearLayoutManager(this,RecyclerView.HORIZONTAL,false));
        classfiyAdapter = new SearchClassfiyAdapter(this);
        rv_class.setAdapter(classfiyAdapter);
        classfiyAdapter.setListener(data -> {
            if (data.getLevel() == 0){
                Intent intent=new Intent(this, TypeListActivity.class);
                intent.putExtra("TAG","ReaderItemProvider");
                intent.putExtra("Title",getTypeName(data.getType()+""));
                intent.putExtra("ReaderTypeId",data.getReaderTypeId());
                intent.putExtra("Type",data.getType()+"");
                startActivity(intent);
            }else if (data.getLevel() == 1){
                ReaderTypeList.List news = BeanConvertor.fromBean(data,new ReaderTypeList.List());
                ReaderTypeList.Author author = BeanConvertor.fromBean(data.getAuthor(),new ReaderTypeList.Author());
                news.setAuthor(author);
                Intent intent=new Intent(this, ProjectListActivity.class);
                intent.putExtra("ReaderTypeList",news);
                startActivity(intent);
            }
        });

        main_lv_search_results = findViewById(R.id.main_lv_search_results);
        main_lv_search_results.setLayoutManager(new LinearLayoutManager(this,RecyclerView.VERTICAL,false));
        searchReultListAdapter = new SearchReultListAdapter(this);
//        mSearchTagAdapter = new SearchTagAdapter(SearchNewActivity.this);
        main_lv_search_results.setAdapter(searchReultListAdapter);
        searchReultListAdapter.setListener(new SearchReultListAdapter.ItemClickListener() {
            @Override
            public void onItemClick(ReaderBean.PageListBean data) {
                Intent intent;
                if (data.getType().equals("2")) {
                    intent = new Intent(SearchNewActivity.this, VideoActivity.class);
                    intent.putExtra("TAG", "ReaderItemProvider");
                    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                } else if (data.getType().equals("3")) {
                    intent = new Intent(SearchNewActivity.this, RadioActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                } else {
                    intent = new Intent(SearchNewActivity.this, ArticleActivity.class);
                }
                intent.putExtra("ReaderId", data.getReaderId());
                startActivity(intent);
            }
        });


        ycRefreshView = findViewById(R.id.ycRefreshView);
        ycRefreshView.setVisibility(View.GONE);
        view_lin.setVisibility(View.GONE);
        ycRefreshView.setEmptyView(R.layout.item_error);
//        //RecylerViewUtils.attachGridLayoutRv(SearchNewActivity.this, main_lv_search_results, RecylerViewUtils.UNSET_GRID);
//        mSearchTagAdapter.setOnItemClickListener(new OnItemClickListener() {
//            @Override
//            public void onItemClick(int position) {
//                search_et_input.setText(mReaderTagList.get(position).getName());
//                getTagReaderList(mReaderTagList.get(position).getId());
//            }
//        });
        mTagReaderListAdapter = new TagReaderListAdapter(mTagReaderList, SearchNewActivity.this);
        ycRefreshView.setAdapter(mTagReaderListAdapter);
        ycRefreshView.setErrorView(R.layout.item_error);
        ycRefreshView.setEmptyView(R.layout.item_error);
        //ycRefreshView.setLayoutManager(new LinearLayoutManager(SearchNewActivity.this));
        GridLayoutManager manager = new GridLayoutManager(this, 3);
        // 设置布局管理一条数据占用几行，如果是头布局则头布局自己占用一行
        try {
            manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int postion) {
                    if (mTagReaderList.get(postion) instanceof TagReaderList.ReaderType) {
                        return 1;
                    } else if (mTagReaderList.get(postion) instanceof TagReaderList.Reader) {
                        return 3;
                    } else if (mTagReaderList.get(postion) instanceof ReaderTwo) {
                        return 3;
                    } else {
                        return 3;
                    }
                }
            });
            ycRefreshView.setLayoutManager(manager);
        } catch (Exception e) {
            e.printStackTrace();
        }
        tv_cacel = findViewById(R.id.tv_cacel);
        tv_cacel.setOnClickListener(v -> {
            if(ycRefreshView.getVisibility()==View.GONE){
                finish();
            }
            ycRefreshView.setVisibility(View.GONE);
            view_lin.setVisibility(View.GONE);
            search_et_input.setText("");
            //main_lv_search_results.setVisibility(View.VISIBLE);
        });
        authorWidget = findViewById(R.id.authorWidget);
    }

//    private void getTagReaderList(int tag) {
//        mTagReaderList.clear();
//        HashMap postMap = new HashMap();
//        MyOkHttpClient.getInstance().asyncJsonPostNoToken(Urls.getTagReaderList(tag, 1, 100), postMap, new MyOkHttpClient.HttpCallBack() {
//            @Override
//            public void onError(Request request, IOException e) {
//
//            }
//
//            @Override
//            public void onSuccess(Request request, String result) {
//                //main_lv_search_results.setVisibility(View.GONE);
//                TagReaderList tagReaderList = gson.fromJson(result, TagReaderList.class);
//
//                for (int i = 0; i < tagReaderList.getPage().getList().size(); i++) {
//                    TagReaderList.ReaderType mReader = tagReaderList.getPage().getList().get(i).getReaderType();
//                    if (tagReaderList.getPage().getList().get(i).getReaderType() != null) {
//                        mTagReaderList.add(mReader);
//                    }
//                }
//                for (int i = 0; i < tagReaderList.getPage().getList().size(); i++) {
//                    TagReaderList.ReaderType mReader = tagReaderList.getPage().getList().get(i).getReaderType();
//                    if (tagReaderList.getPage().getList().get(i).getReaderType() != null) {
//                        ReaderTwo readerTwo = new ReaderTwo();
//                        readerTwo.setSynopsis(mReader.getSynopsis());
//                        readerTwo.setAuthorId(mReader.getAuthorId());
//                        readerTwo.setType(mReader.getType());
//                        readerTwo.setTagName(mReader.getTagName());
//                        readerTwo.setTagIds(mReader.getTagIds());
//                        readerTwo.setReaderTypeId(mReader.getReaderTypeId());
//                        readerTwo.setCreateTime(mReader.getCreateTime());
//                        readerTwo.setDoubSort(mReader.getDoubSort());
//                        readerTwo.setIcon(mReader.getIcon());
//                        readerTwo.setIsShow(mReader.getIsShow());
//                        readerTwo.setReadAmount(mReader.getReadAmount());
//                        readerTwo.setLevel(mReader.getLevel());
//                        readerTwo.setReaderTypeId(mReader.getReaderTypeId());
//                        readerTwo.setName(mReader.getName());
//                        readerTwo.setOpen(mReader.getOpen());
//                        readerTwo.setParentIdLink(mReader.getParentIdLink());
//                        readerTwo.setParentName(mReader.getParentName());
//                        readerTwo.setPyFull(mReader.getPyFull());
//                        readerTwo.setPyShort(mReader.getPyShort());
//                        readerTwo.setReadAmount(mReader.getReadAmount());
//                        readerTwo.setTotal(mReader.getTotal());
//                        readerTwo.setUpdateTime(mReader.getUpdateTime());
//                        mTagReaderList.add(readerTwo);
//                    }
//                }
//                for (int i = 0; i < tagReaderList.getPage().getList().size(); i++) {
//                    TagReaderList.Reader mReader1 = tagReaderList.getPage().getList().get(i).getReader();
//                    if (mReader1 != null) {
//                        mTagReaderList.add(mReader1);
//                    }
//                }
//                if (tagReaderList.getCode() == 0) {
//                    view_lin.setVisibility(View.VISIBLE);
//                    ycRefreshView.setVisibility(View.VISIBLE);
//                    mTagReaderListAdapter.notifyDataSetChanged();
//                }else{
//                    ycRefreshView.setEmptyView(R.layout.item_error);
//                }
//            }
//        });
//    }

    private String getTypeName(String type){
        if ("1".equals(type)){
            return "阅读";
        }else if ("2".equals(type)){
            return "视屏";
        }else {
            return "聆听";
        }
    }
}
